package Helper;

import android.os.Environment;

import com.example.administrator.drinkdevice.BuildConfig;

import java.io.File;
import java.io.FileFilter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;


public class PrintLog {

    private String packageName;

    private void DeleteDir(String dirName) {
        File df = new File(dirName);
        if (df == null) {
            return;
        }
        File[] flist = df.listFiles();
        for (File f : flist) {
            if (f.isDirectory()) {
                File[] childFile = f.listFiles();
                if (childFile == null || childFile.length == 0) {
                    f.delete();
                    continue;
                }
                for (File sf : childFile) {
                    if (sf.isDirectory()) {
                        DeleteDir(sf.getAbsolutePath());
                    } else {
                        sf.delete();
                    }
                }
                f.delete();
            } else {
                f.delete();
            }
        }
        df.delete();
    }
    public PrintLog() {
        //String[] applicationId = BuildConfig.APPLICATION_ID.split("\\.");
        packageName = BuildConfig.FLAVOR;
        String filePath = Environment.getExternalStorageDirectory().getPath() +"/"+packageName+"/";
        File Logfile = new File(filePath);
        File[] flist=Logfile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if(file.getName().indexOf(".db")>=0) {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        });
        if (flist==null)
        {
            return;
        }
        for ( File f:flist ) {
            long time = f.lastModified();//返回文件最后修改时间，是以个long型毫秒数
            String ctime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(time));
            int daynumber = (int) EnjoyTools.dateDiff(ctime, EnjoyTools.getDatetimeStr("yyyy-MM-dd"), "yyyy-MM-dd");
            if (daynumber>=7) {
                if (f.isDirectory())
                {
                    DeleteDir(f.getAbsolutePath());
                }
                else
                {
                    f.delete();
                }
            }
        }
        packageName =String.format("%s/Log_%s", BuildConfig.FLAVOR,EnjoyTools.getDatetimeStr("yyyy-MM-dd"));// applicationId[applicationId.length-1];
    }

    // 生成日志 打印日志 log TxT 专用
    public void printLogMsg(String tag, String msg) {

        String filePath = Environment.getExternalStorageDirectory().getPath() +"/"+packageName+"/";
        if (tag.lastIndexOf("/")>=0)
        {
            tag= tag.substring(tag.lastIndexOf("/")+1);
        }
        String fileName =String.format( "%s.txt",tag);

        writeTxtToFile(msg, filePath, fileName);


    }
    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时,都换行写
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
        String strContent = sdf.format(new Date())+" "+strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                android.util.Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            if (file.length()<=0)
            {
                raf.write(String.format("======================== 版本：%s =======================\r\n", BuildConfig.VERSION_NAME).getBytes());
            }
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            android.util.Log.d("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            Log.write("Exception",sw.toString());
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            android.util.Log.d("error:", e+"");
        }
    }
}
